import { computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { hasPermission } from '@/utils/permission'
import * as permissionApi from '@/api/permission'
import type { SysPermission, PermissionTreeNode } from '@/types/permission'

export function usePermission() {
  const authStore = useAuthStore()
  
  /**
   * 判断是否有权限
   * @param permissionKey 权限标识
   * @returns 是否有权限
   */
  const checkPermission = (permissionKey: string): boolean => {
    return hasPermission(permissionKey)
  }
  
  /**
   * 根据角色ID获取权限树
   * @param roleId 角色ID
   */
  const getRolePermissionTree = async (roleId: number) => {
    try {
      return await permissionApi.getRolePermissionTree(roleId)
    } catch (error) {
      console.error('获取角色权限树失败:', error)
      return { permissionTree: [], checkedKeys: [] }
    }
  }
  
  /**
   * 获取权限列表
   */
  const getPermissionList = async () => {
    try {
      return await permissionApi.getPermissionList()
    } catch (error) {
      console.error('获取权限列表失败:', error)
      return []
    }
  }
  
  /**
   * 将权限列表转换为树形结构
   * @param permissions 权限列表
   * @returns 权限树
   */
  const convertToTree = (permissions: SysPermission[]): PermissionTreeNode[] => {
    // 深拷贝原始数据
    const permissionsCopy: PermissionTreeNode[] = JSON.parse(JSON.stringify(permissions))
    
    // 转换为树形结构所需的格式
    permissionsCopy.forEach(item => {
      item.key = item.permissionId
      item.title = item.permissionName
    })
    
    // 映射关系表
    const map = new Map<number, PermissionTreeNode>()
    permissionsCopy.forEach(item => map.set(item.permissionId, item))
    
    // 生成树形结构
    const result: PermissionTreeNode[] = []
    permissionsCopy.forEach(item => {
      const parent = map.get(item.parentId)
      if (parent) {
        // 父节点存在，添加到父节点的children
        parent.children = parent.children || []
        parent.children.push(item)
      } else {
        // 父节点不存在，是顶级节点
        result.push(item)
      }
    })
    
    return result
  }
  
  // 用户权限列表
  const permissions = computed(() => authStore.permissions)
  
  // 用户角色列表
  const roles = computed(() => authStore.roles)
  
  // 是否是管理员
  const isAdmin = computed(() => authStore.isAdmin)
  
  return {
    checkPermission,
    getRolePermissionTree,
    getPermissionList,
    convertToTree,
    permissions,
    roles,
    isAdmin
  }
}
